package com.yuxi.distributelock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Created by yuxi on 16/12/27.
 */
@RestController
@RequestMapping("/redis")
public class TestRedisLock {
    @Autowired
    private RedisLock redisLockService;

    @RequestMapping("/test")
    public void testRedisDistributionLock() {
        for (int i = 1; i < 200; i++) {
            final int finalI = i;
            new Thread(new Runnable() {

                @Override
                public void run() {
                    task(Thread.currentThread().getName());
                }
            }).start();
        }
        try {
            TimeUnit.MINUTES.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void task(String name) {
        try {
            Boolean success = redisLockService.lock(String.valueOf(1));
            if (success) {
                System.out.println("加锁时间后处理时间为" + "key值为=====" + Thread.currentThread().getName());
                redisLockService.unlock(String.valueOf(1));
            } else {
                System.out.println("拿不到锁" + "key值为=====" + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
